"""
管理后台 - 用户管理接口
"""
from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.ext.asyncio import AsyncSession

from app.dependencies import get_db, get_current_user
from app.schemas.common import ResponseModel, PaginatedResponse
from app.schemas.user import UserCreate, UserUpdate, UserResponse
from app.crud import user as crud_user


router = APIRouter()


@router.get("", response_model=ResponseModel)
async def get_users(
    page: int = Query(1, ge=1),
    page_size: int = Query(10, ge=1, le=100),
    db: AsyncSession = Depends(get_db),
    current_user = Depends(get_current_user)
):
    """
    获取用户列表
    """
    skip = (page - 1) * page_size
    users = await crud_user.user.get_multi(db, skip=skip, limit=page_size)
    total = await crud_user.user.get_count(db)
    
    return ResponseModel(
        data=PaginatedResponse(
            total=total,
            page=page,
            page_size=page_size,
            items=[UserResponse.model_validate(u) for u in users]
        )
    )


@router.get("/{user_id}", response_model=ResponseModel)
async def get_user(
    user_id: int,
    db: AsyncSession = Depends(get_db),
    current_user = Depends(get_current_user)
):
    """
    获取用户详情
    """
    user = await crud_user.user.get_by_id(db, id=user_id)
    if not user:
        raise HTTPException(status_code=404, detail="用户不存在")
    
    return ResponseModel(data=UserResponse.model_validate(user))


@router.post("", response_model=ResponseModel)
async def create_user(
    user_in: UserCreate,
    db: AsyncSession = Depends(get_db),
    current_user = Depends(get_current_user)
):
    """
    创建用户
    """
    # 检查用户名是否已存在
    existing_user = await crud_user.user.get_by_username(db, username=user_in.username)
    if existing_user:
        raise HTTPException(status_code=400, detail="用户名已存在")
    
    # 检查邮箱是否已存在
    existing_email = await crud_user.user.get_by_email(db, email=user_in.email)
    if existing_email:
        raise HTTPException(status_code=400, detail="邮箱已存在")
    
    user = await crud_user.user.create(db, obj_in=user_in)
    return ResponseModel(
        code=201,
        message="创建成功",
        data=UserResponse.model_validate(user)
    )


@router.put("/{user_id}", response_model=ResponseModel)
async def update_user(
    user_id: int,
    user_in: UserUpdate,
    db: AsyncSession = Depends(get_db),
    current_user = Depends(get_current_user)
):
    """
    更新用户
    """
    user = await crud_user.user.get_by_id(db, id=user_id)
    if not user:
        raise HTTPException(status_code=404, detail="用户不存在")
    
    user = await crud_user.user.update(db, db_obj=user, obj_in=user_in)
    return ResponseModel(
        message="更新成功",
        data=UserResponse.model_validate(user)
    )


@router.delete("/{user_id}", response_model=ResponseModel)
async def delete_user(
    user_id: int,
    db: AsyncSession = Depends(get_db),
    current_user = Depends(get_current_user)
):
    """
    删除用户
    """
    # 不允许删除自己
    if user_id == current_user.id:
        raise HTTPException(status_code=400, detail="不能删除自己")
    
    success = await crud_user.user.delete(db, id=user_id)
    if not success:
        raise HTTPException(status_code=404, detail="用户不存在")
    
    return ResponseModel(message="删除成功")

